<template>
  <!-- 自有计量设备台账 -->
  <base-breadcrumb :title="$route.meta.title">
    <!-- 搜索 -->
    <searchData :searchData="searchArr" @search="search" @hasChildren="isHasChildren"></searchData>
    <!-- 表格 -->
    <a-card :bordered="false">
      <list-table ref="table" :loading="loading" tableLayout="fixed" size="default"
                  :columns="columns" :request="loadData"
                  :statistics-config="{ use: true, statistics, temp }"
                  :selectConfig="{ use: true, type: 'checkbox', rowKey: 'id' }" :export-config="{
                            use: true,
                            all: exportConfig.all,
                            select: exportConfig.select,
                        }" :export-config-text="{ select: '导出选中', all: '导出全部' }"
                  :exportPermission="{select: 'qm_062_aexp_07',all: 'qm_062_sexp_06'}"
                  @exportSelect="exportSelect" @exportAll="exportAll">
        <template slot="mdStatus" slot-scope="text, record">
          <span v-if="record.mdStatus">
            {{ getArrayLable(equipmentStatusArr,record.mdStatus) }}
          </span>
        </template>
        <template slot="appraisalStatus" slot-scope="text, record">
          <span v-if="record.appraisalStatus">
            {{ getArrayLable(checkStatusArr,record.appraisalStatus) }}
          </span>
        </template>
        <template slot="prefix">
          <a-button icon="plus" v-btn-permission="'qm_062_add_01'" v-if="hideBuquBtn()"
                    type="primary" @click="handleManage(2)">新增</a-button>
        </template>
        <template slot="actions" slot-scope="text, record">
          <MoreButton>
            <a v-btn-permission="'qm_062_loo_03'" @click="handleManage(0, record)">查看</a>
            <a v-btn-permission="'qm_062_edi_02'" v-if="record.mdStatus == '0' && hideBuquBtn()"
               @click="handleManage(1, record)">编辑</a>
            <a v-if="(record.mdStatus == '0' || record.mdStatus == '1' || record.mdStatus == '3') && hideBuquBtn()"
               v-btn-permission="'qm_062_doc_04'" @click="docimasy(record)">检定</a>
            <a v-btn-permission="'qm_062_dt_05'" @click="updateStatus(record,0)"
               v-if="record.mdStatus == '9' && hideBuquBtn()">启用</a>
            <a v-btn-permission="'qm_062_dt_05'" v-if="record.mdStatus == '0' && hideBuquBtn()"
               @click="updateStatus(record,1)">停用</a>
          </MoreButton>
        </template>
      </list-table>
    </a-card>
    <!-- 计量设备检定记录弹窗 -->
    <equipment-modal ref="equipmentModal" :modalData="modalData"
                     @handle-table-refresh="handleTableRefresh"></equipment-modal>
  </base-breadcrumb>
</template>

<script>
import api from '@/api/quality/ownEquipmentLedger' // api
import dataFilter from '../constant/dataFilter'
import { getArrayLable } from '@/views/quality/equipmentManagement/constant/getArrayLable'
import handleDownload from '@/views/quality/equipmentManagement/constant/downloadFile.js'
import { equipmentStatusArr, checkStatusArr } from '@/views/quality/equipmentManagement/constant/dictionary'
import OrgTreeSelect from '@/components/OrgTreeSelect'
import { verificationModal } from '../projectMeterageEquipmentAccount/components/equipmentModal.js'
import EquipmentModal from '../projectMeterageEquipmentAccount/components/equipmentModal.vue'
export default {
  name: "ownEquipmentLedgerList",
  components: {
    EquipmentModal
  },
  data() {
    return {
      loading: false,
      exportConfig: {
        all: '自有计量设备台账列表-导出全部',
        select: '自有计量设备台账列表-导出选中'
      },
      queryParam: {},// 查询参数
      hasChildren: true,
      searchArr: [//查询条件
        {
          name: '设备名称',
          type: 'input',
          value: 'mdInfoName',
        },
        {
          name: '规格型号',
          type: 'input',
          value: 'mdModelName',
        },
        {
          name: '设备编号',
          type: 'input',
          value: 'mdCode',
        },
        {
          name: '设备状态',
          type: 'select',
          value: 'mdStatus',
          data: dataFilter(equipmentStatusArr, ['0', '1', '2', '3', '4', '9'])
        },
        {
          name: '检定状态',
          type: 'select',
          value: 'appraisalStatus',
          data: checkStatusArr
        },
      ],
      columns: [//表格列定义
        {
          title: '序号',
          width: 80,
          dataIndex: 'index',
          customRender() {
            return arguments[2] + 1
          }
        },
        {
          title: '设备编号',
          ellipsis: true,
          dataIndex: 'mdCode'
        },
        {
          title: '设备名称',
          ellipsis: true,
          dataIndex: 'mdName'
        },
        {
          title: '规格型号',
          ellipsis: true,
          dataIndex: 'specificationModel'
        },
        {
          title: '分公司',
          ellipsis: true,
          dataIndex: 'branchCompanyName'
        },
        {
          title: '当前所在项目',
          ellipsis: true,
          dataIndex: 'projectName'
        },
        {
          title: '设备状态',
          ellipsis: true,
          dataIndex: 'mdStatus',
          scopedSlots: { customRender: 'mdStatus' }
        },
        {
          title: '检定状态',
          ellipsis: true,
          dataIndex: 'appraisalStatus',
          scopedSlots: { customRender: 'appraisalStatus' }
        },
        {
          title: '操作',
          dataIndex: 'actions',
          width: '230px',
          fixed: 'right',
          scopedSlots: { customRender: 'actions' }
        }
      ],
      editModel: 0,
      modalData: {},//[检定]弹窗数据列
      equipmentStatusArr, //设备状态
      checkStatusArr,//检定状态
      api,// api
      totalSize: 0,
      statistics: {
        companyFreeCount: 0,
        projectFreeCount: 0,
        transferCount: 0,
        useCount: 0,
        returnCount: 0,
        disableCount: 0,
        qualifiedCount: 0,
        unqualifiedCount: 0
      },
      temp: () => {
        return (
          <span style="margin-right: 12px">
            公司闲置：<span class="totalNum">{this.statistics.companyFreeCount || 0} 个</span> |
            项目闲置：<span class="totalNum">{this.statistics.projectFreeCount || 0} 个</span> |
            调拨中：<span class="totalNum">{this.statistics.transferCount || 0} 个</span> |
            使用中：<span class="totalNum">{this.statistics.useCount || 0} 个</span> |
            归还中：<span class="totalNum">{this.statistics.returnCount || 0} 个</span> |
            停用：<span class="totalNum">{this.statistics.disableCount || 0} 个</span> |
            检定合格：<span class="totalNum">{this.statistics.qualifiedCount || 0} 个</span> |
            检定不合格：<span class="totalNum">{this.statistics.unqualifiedCount || 0} 个</span>
          </span>
        )
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let { pageNo, pageSize } = parameter;
        let params = {
          pageNum: pageNo,
          pageSize
        };
        const requestParameters = Object.assign({}, params, { param: this.setQueryParam() })
        this.loading = true;
        return this.api.list(requestParameters).then((res) => {
          this.loading = false;
          if (res.code === '0') {
            return { code: 200, data: res.data?.list, totalSize: res.data?.total }
          }
        }).catch((err) => {
          this.loading = false;
        })
      },
    }
  },
  created() {
    //不是业务查询模块才展示
    if (this.hideBuquBtn()) {
      this.searchArr.unshift({
        name: '所属单位',
        valueKey: 'searchQuery',
        type: OrgTreeSelect,
      })
    }
    this.getCountByMdStatus();
  },
  methods: {
    /**
 * @description: 设置查询参数
 */
    setQueryParam() {
      const requestParameters = Object.assign({}, this.queryParam)
      //选中包含下级或者输入框未选中值的情况下传递此参数
      if (this.hasChildren || !requestParameters.searchQuery || requestParameters.searchQuery._checked == '') {
        requestParameters.permissionType = "1"
      }
      return requestParameters
    },
    isHasChildren(val) {
      this.hasChildren = val;
    },
    /**
     * @description: 获取统计数量
     */
    getCountByMdStatus() {
      this.api
        .getCountByMdStatus(this.setQueryParam())
        .then((res) => {
          if (res.code === '0') {
            this.statistics = res.data;
          }
        })
        .catch((error) => {
          console.log(error)
        })
    },
    /**
    * @description: 导出选中
    * @param {Arrary} data 选中的数据
    */
    exportSelect(data) {
      const idList = data.map(item => item.id)
      const requestParameters = Object.assign({}, this.setQueryParam())
      requestParameters.ids = idList;
      handleDownload(this.api.exportData, requestParameters, this.exportConfig.select)
    },
    /**
    * @description: 导出全部
    */
    exportAll() {
      handleDownload(this.api.exportData, this.setQueryParam(), this.exportConfig.all)
    },
    /**
     * @description:获取数组的label
     */
    getArrayLable,
    /**
    * @description:搜索
    * @param {Object} val 筛选项
    */
    search(val) {
      this.queryParam = { ...val }
      this.getCountByMdStatus();
      this.$refs.table.refresh()
    },
    /**
    * @description:查看/编辑/新增
    * @param {Number} type 0:查看 1:编辑 2:新增
    * @param {Object} record 当前行数据
    */
    handleManage(type, record) {
      this.editModel = type
      let query = {
        editModel: type,
        isOwn: true
      }
      if (type == 0) {
        let _obj = { isShowAllotRecord: true, isShowVerifRecord: true }
        query = { ...query, ..._obj }
      }
      if (record && record.id) {
        query.id = record.id
      }
      this.$router.push({
        name: 'ownEquipmentLedgerInfo',
        query
      })
    },
    /**
    * @description:刷新表格
    */
    handleTableRefresh() {
      this.$refs.table.refresh(true)
    },
    /**
    * @description:检定
    * @param {Object} record 当前行数据
    */
    docimasy(record) {
      verificationModal.api = this.api.certifiedOwnEquipment;
      this.modalData = verificationModal;
      this.modalData.form = record;
      this.$refs.equipmentModal.toggleVisible()
    },
    /**
     * @description:停用/启用
     * @param {Object} record 当前行数据
     * @param {Number} num 0:启用 1:停用
     */
    updateStatus(record, num) {
      let that = this
      let { id, mdStatus } = record;
      let _text = ['启用', '停用'][num] || '操作'
      let _newStatus = mdStatus == '9' ? '0' : '9'
      that.$confirm({
        title: '温馨提示',
        content: `确认${_text}？`,
        okText: '确认',
        cancelText: '关闭',
        onOk() {
          that.api
            .updateMdStatus({ id, mdStatus: _newStatus })
            .then((res) => {
              if (res.code === '0') {
                that.$message.success(_text + '成功！')
                that.$refs.table.refresh(true)
              }
            })
            .catch((error) => {
              console.log(error)
            })
        }
      })
    },
  }
}
</script>

<style>
</style>